package com.example.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class NotifyFreeLock2LockSupport {

    //添加volatile，使t2能够得到通知
    volatile List lists = new ArrayList();

    public  void add(Object o) {
        lists.add(o);
    }
    public static void main(String[] args) throws Exception{
        NotifyFreeLock2LockSupport notifyFreeLock = new NotifyFreeLock2LockSupport();

        Thread t2 =  new Thread(()->{
            LockSupport.park();
            if (notifyFreeLock.lists.size()==5){
                System.out.println("线程2=="+notifyFreeLock.lists.size());

            }
        });

        Thread t1 =  new Thread(()->{
            for(int i=0;i<10;i++){
                notifyFreeLock.add(new Object());
                System.out.println("添加对象 size="+notifyFreeLock.lists.size());
                if (notifyFreeLock.lists.size()==5){
                    LockSupport.unpark(t2);
                    try {
                        t2.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t1.start();
        t2.start();
    }
}
